﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using Domain;

namespace ExcelUploadPoc.Controllers
{
  public class RegionController : Controller
  {
    //
    // GET: /Region/

    EFDbContext db = new EFDbContext();

    public ActionResult Index()
    {
      return View(db.Regions.Where(x => x.Parent == null).ToList());
    }

    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
      if (file != null && file.ContentLength > 0 && file.ContentType == "application/vnd.ms-excel")
      { //only allow csv files
        string path = Path.Combine(Server.MapPath("~/Upload"), file.FileName);
        file.SaveAs(path);

        string line;
        using (StreamReader r = new StreamReader(path))
        {
          Dictionary<int, Region> lastItems = new Dictionary<int, Region>();
          while ((line = r.ReadLine()) != null)
          {
            if (ModelState.IsValid)
            {
              string[] values = line.Split(';');
              for (int i = 0; i < values.Length; i++)
              {
                if (values[i].Equals("")) { continue; }
                Region region = new Region();
                region.Name = values[i];
                region.DateJoined = DateTime.Today;
                if (lastItems.ContainsKey(i - 1))
                {
                  region.Parent = lastItems[i - 1];
                }
                lastItems.Remove(i);
                lastItems.Add(i, region);
                db.Regions.Add(region);
              }
              db.SaveChanges();
            }
          }
        }
      }

      return RedirectToAction("Index");
    }

  }
}
